<template>
  <el-form
    v-loading="tableLoading"
    :element-loading-spinner="loadingSpinner"
    element-loading-svg-view-box="0,0, 1024, 1024"
    ref="TrendsTableFormRef"
    style="width: 100%"
    :model="tableFormData"
    status-icon
  >
    <div class="header">
      <!-- 左边 -->
      <div class="header-left">
        <!-- 错误提示 -->
        <ErrTips
          ref="ErrTipsRef"
          :topExpose="topExpose"
          :tableInfo="_info"
          class="mb-10"
        />
      </div>
      <!-- 右边-按钮 -->
      <div class="header-right">
        <!-- 新增行数 -->
        <AddLine
          v-if="canAdd(_rules, _info)"
          :_rules="_rules"
          class="mb-10"
          @addRow="addRow"
        />
      </div>
    </div>
    <el-table :data="tableData" border row-key="tableId">
      <!-- 序号 -->
      <el-table-column fixed="left" align="center" label="序号" width="60">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in _children"
        :key="getTableProp(item)"
        :prop="getTableProp(item)"
        :label="item.info.name"
        :min-width="item.info.width || 100"
        align="center"
      >
        <template #header>
          <span v-if="isRequired(item)" class="danger-text">*</span>
          {{ item.info.name }}
        </template>
        <template #default="{ row, $index }">
          <div
            class="column-box"
            v-loading="row.renderLoading"
            :element-loading-spinner="loadingSpinner"
            element-loading-svg-view-box="0,0, 1024, 1024"
          >
            <div class="column-content">
              <!-- 只读 -->
              <template v-if="getColumnInfo(row, item).read_only">
                <ReadOnly
                  :columnInfo="getColumnInfo(row, item)"
                  :columnItem="item"
                />
              </template>
              <!-- 编辑 -->
              <el-form-item
                v-else
                style="width: 100%"
                :prop="getFormProp(item, $index)"
                :rules="setRules(row, item)"
              >
                <!-- 输入框 -->
                <Input
                  v-if="getColumnInfo(row, item).field_type === 'input'"
                  :tableFormData="tableFormData"
                  :index="$index"
                  :columnInfo="getColumnInfo(row, item)"
                />
                <!-- 数字输入 -->
                <Input-Number
                  v-else-if="
                    getColumnInfo(row, item).field_type === 'input_number'
                  "
                  :tableFormData="tableFormData"
                  :index="$index"
                  :columnInfo="getColumnInfo(row, item)"
                />
                <!-- 下拉 -->
                <Select
                  v-else-if="getColumnInfo(row, item).field_type === 'select'"
                  :tableFormData="tableFormData"
                  :index="$index"
                  :columnItem="item"
                  :formData="formData"
                  :topExpose="topExpose"
                  :tableData="tableData"
                  :row="row"
                  :columnInfo="getColumnInfo(row, item)"
                  :tableInfo="_info"
                  :formInfo="formInfo"
                />
              </el-form-item>
            </div>
            <!-- 单位 -->
            <span v-if="getColumnInfo(row, item).unit" class="ml-5 column-unit">
              {{ getColumnInfo(row, item).unit }}
            </span>
          </div>
        </template>
      </el-table-column>
      <!-- 删除按钮 -->
      <el-table-column
        v-if="canAdd(_rules, _info)"
        fixed="right"
        align="center"
        label="操作"
        width="70"
      >
        <template #default="{ row }">
          <el-button
            link
            type="danger"
            :disabled="
              row.renderLoading || tableData.length <= _rules.min_array
            "
            @click="delRow(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加按钮 -->
    <div class="add-row" v-if="canAdd(_rules, _info)" @click="addRow(1)">
      <el-icon><CirclePlus /></el-icon>
      <span class="ml-5">添加</span>
    </div>
  </el-form>
</template>

<script setup>
import {
  getTableProp,
  getFormProp,
  getColumnInfo,
  setRules,
  isRequired,
  getOptions,
  canAdd
} from './const';
import { getInfo, getRules } from '../const';
import { loadingSpinner } from '@/assets/js/loadingIcon.js';
import ReadOnly from './ReadOnly';
import Input from './Input';
import InputNumber from './InputNumber';
import Select from './Select';
import ErrTips from './ErrTips';
import AddLine from './AddLine';
const props = defineProps({
  formInfo: {
    type: Object,
    default: () => {}
  },
  formData: {
    type: Object,
    default: () => {}
  },
  TrendsFormRef: {
    type: Object,
    default: null
  },
  topExpose: {
    type: Object,
    default: () => {}
  }
});

const _children = computed(() => props.formInfo?.children || []);
const _info = computed(() => getInfo(props.formInfo));
const _rules = computed(() => getRules(props.formInfo));

// 获取下拉值
function getTableOptions() {
  const typeList = ['select'];
  _children.value.forEach(item => {
    if (!typeList.includes(item.info.field_type)) return;
    getOptions({
      item,
      form_uni_key: props.topExpose.form_uni_key,
      form_role: props.topExpose.form_role,
      initValues: props.topExpose.initValues
    });
  });
}
getTableOptions();

// 表格数据
let tableId = 1;
const tableData = computed(() => {
  if (!props.formInfo.table) props.formInfo.table = [];
  const _table = props.formInfo?.table;
  return _table.map(item => {
    const obj = {};
    (item || []).forEach(it => {
      obj[getTableProp(it)] = it;
    });
    if (!obj.tableId) obj.tableId = tableId++;
    return obj;
  });
});

// 获取表单对象
const tableFormData = ref([]);
const TrendsTableFormRef = ref();
function getFormObj() {
  const _field = _info.value.field;
  const _formData = props.formData;
  _formData[_field] = [];
  // 填充值
  tableData.value.forEach((item, index) => {
    _formData[_field][index] = {};
    Object.keys(item).forEach(key => {
      if (key === 'tableId') return;
      const info = item[key]?.info || {};
      _formData[_field][index][key] = info.value;
    });
  });
  tableFormData.value = _formData[_field];
  setTimeout(() => {
    const tvlist = props.topExpose.tableValidList.value;
    const index = tvlist.findIndex(item => item.field === _field);
    if (index >= 0) tvlist.splice(index, 1);
    tvlist.push({
      validFn: valid,
      field: _field,
      tableData: tableFormData,
      tableChildren: props.formInfo.children
    });
  }, 0);
}
getFormObj();

// 表格校验
const tableLoading = ref(false);
const ErrTipsRef = ref();
function valid() {
  return new Promise(async (resolve, reject) => {
    try {
      tableLoading.value = true;
      await TrendsTableFormRef.value.validate();
      await ErrTipsRef.value.validate();
      tableLoading.value = false;
      resolve();
    } catch {
      tableLoading.value = false;
      reject();
    }
  });
}

// 添加n行
function addRow(num) {
  if (props.formInfo?.table?.length + num > _rules.value.max_array) {
    return $msg.warning(
      `已有【${
        props.formInfo?.table?.length
      }】行，本次新增【${num}】行，合计【${
        props.formInfo?.table?.length + num
      }】行，超出最大行数【${_rules.value.max_array}】行限制`
    );
  }
  for (let i = 0; i < num; i++) {
    props.formInfo?.table.push(JSON.parse(JSON.stringify(_children.value)));
    tableFormData.value.push({});
  }
}

// 删除一行
async function delRow(row) {
  const index = tableData.value.findIndex(item => item.tableId === row.tableId);
  props.formInfo?.table.splice(index, 1);
  await nextTick();
  tableFormData.value.splice(index, 1);
  setTimeout(() => {
    TrendsTableFormRef.value.clearValidate();
  }, 0);
}
</script>

<style lang="scss" scoped>
.add-row {
  border: 1px solid var(--el-border-color-lighter);
  border-top: none;
  text-align: center;
  color: var(--el-color-primary);
  cursor: pointer;
  transition: all 0.2s;
  padding: 5px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
  &:hover {
    color: var(--el-color-primary-light-4);
  }
}
.header-right {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  flex: 1;
  max-width: 250px;
}
.column-box {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.column-content {
  flex: 1;
}

.header {
  display: flex;
}
.header-left {
  flex: 1;
}
</style>
